/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quizzempire.model.statemachine;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import quizzempire.model.Model;
import quizzempire.model.Quizz;

/**
 *
 * @author Paulo
 */
public class PrepareGame extends State {

    public PrepareGame(Model modelo) {
        super(modelo);
        modelo.updateQuizzList();
    }

    @Override
    public State startGame(int quizzId, int difficulty) {
        
        if (difficulty < 0 || difficulty > 2)
            return this;
        
        String path;
        
        try {
            path = modelo.getQuizzesFolder() + File.separator + modelo.getQuizzFileName(quizzId);
        } catch (Exception ex) {
            Logger.getLogger(PrepareGame.class.getName()).log(Level.SEVERE, null, ex);
            return this;
        }
        
        File file = new File(path);
        
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        
            Quizz load = (Quizz) ois.readObject();
                        
            if (load.getDifAvailable()[difficulty] == false)
                return this;
            
            modelo.setActiveQuizz(load);
            modelo.setChanges();
            return new AwaitsAnswer(modelo, difficulty);
            
        } catch (IOException ex) {
            Logger.getLogger(PrepareGame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PrepareGame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return this;
    }
    
    @Override
    public State restart() {
        modelo.setChanges();
        return new AwaitsInstruction(modelo);
    }
    
}
